package com.jwsoft.manager.core.integration.eduAddressTree;

import com.jwsoft.manager.common.vo.eduAddressTree.EduAddressTreeVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
//@Component
public class TreeNodeChangeAspect {
    private static final List<AddressTreeObserver> OBSERVER_LIST = new ArrayList<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    protected void init() {
        //初始化观察者
        log.info("初始化观察者");
        String[] beanNames = applicationContext.getBeanNamesForType(AddressTreeObserver.class);
        for (String beanName : beanNames) {
            OBSERVER_LIST.add((AddressTreeObserver) applicationContext.getBean(beanName));
        }
    }

    //切面，监听EduAddressTreeIntegrationImpl下的所有方法
    @Pointcut("within(com.jwsoft.manager.core.integration.eduAddressTree.impl.EduAddressTreeIntegrationImpl)")
    public void a() {
    }

    /**
     * 匹配到a()切点，
     * After在切点下方法执行之后执行treeChangeAfter（）方法
     * 得到线程变量中的treeChange，然后调用treeChangeAfter方法
     */
    @After("a()")
    public void treeChangeAfter() {
        List<EduAddressTreeVO> treeChange = TreeChangeHelper.getTreeChange();
        if (CollectionUtils.isEmpty(treeChange)) {
            return;
        }
        try {
            this.notifyObserver(treeChange);
        } finally {
            TreeChangeHelper.clear();
        }
    }


    /**
     * 通知观察者
     *
     * @author fangs
     */
    private void notifyObserver(List<EduAddressTreeVO> changeList) {
        for (AddressTreeObserver observer : OBSERVER_LIST) {
            observer.invoke(changeList);
        }
    }
}
